//
//  AppDelegate+System.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import FBSDKCoreKit
import GoogleSignIn

//MARK: - 三方回调接口
extension AppDelegate {
    // 从其他App到自己App调用此方法
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
        if url.description.contains("zuihaixiaoshuo") {
            handleTypeStr(url.absoluteString)
            return true
        }
        if url.scheme == "fb\(WNConfigure.Facebook.appId)", url.host == "bookDetail", let queryStr = url.query, queryStr.count > 0 {
            handleTypeStr(queryStr)
            return true
        }
        if GIDSignIn.sharedInstance.handle(url) {
            return true
        }
        return false
    }
    
    // 从其他App打开自己App
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
            if let url = userActivity.webpageURL {
                if url.absoluteString.hasPrefix(server.APIHost) {
                    if let queryStr = url.query, queryStr.count > 0 {
                        handleTypeStr(queryStr)
                    }
                }            }
        }else {
            return false
        }
        return true
    }
    
    // web端回调到本app的回调
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return true
    }
}

//MARK: - 通知处理
extension AppDelegate: UNUserNotificationCenterDelegate {
    /// 注册通知
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenStr = deviceToken.map { String(format:"%02.2hhx", $0) }.joined()
        WNLog(deviceTokenStr)
    }
    
    /// 注册失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        WNLog(error)
    }
    
    /// 后台接收静默通知
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        guard userInfo["aps"] is [String: AnyObject] else {
            return completionHandler(.failed)
        }
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    /// 后台收到通知处理
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let userInfo = response.notification.request.content.userInfo as? [String: AnyObject], userInfo.count > 0 {
            var str = ""
            for i in userInfo {
                str += "\(i.key)=\(i.value)&"
            }
            str.removeLast()
            handleTypeStr(str)
        }
        completionHandler()
    }
    
    /// 前台收到通知处理
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([])
    }
}

//MARK: - 前后台处理
extension AppDelegate {
    // 被杀死
    func applicationWillTerminate(_ application: UIApplication) {
        if let vc = wn_getTopVC(), vc.isKind(of: WNReadVC.self) {
            if let readVC = vc as? WNReadVC {
                readVC.stopReadTimer()
            }
        }
    }
    
    // 进入后台
    func applicationDidEnterBackground(_ application: UIApplication) {
        if let vc = wn_getTopVC(), vc.isKind(of: WNReadVC.self) {
            if let readVC = vc as? WNReadVC {
                readVC.readingPause(true)
            }
        }

    }
    
    // 回到前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        if let vc = wn_getTopVC(), vc.isKind(of: WNReadVC.self) {
            if let readVC = vc as? WNReadVC {
                readVC.readingPause(false)
            }
        }
        if let vc = wn_getTopVC(), vc.isKind(of: WNSettingVC.self) {
            if let readVC = vc as? WNSettingVC {
                readVC.refreshNot()
            }
        }
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .portrait
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        resignActive = true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        let idfa = requestIDFA()
        let enable = idfa.count != 0 ? true : false
        Settings.shared.isAdvertiserTrackingEnabled = enable // Facebook分享数据
        Settings.shared.isAdvertiserIDCollectionEnabled = enable // 广告主编号收集功能
        WNBuriedManager.shared.active()
        if resignActive {
            resignActive = false
            return
        }else {
            WNBuriedManager.shared.startEvents("start")
        }
    }
}
